﻿#include"ffwebsocket.h"

// 构造函数
FFWebSocket::FFWebSocket()
{
}

// 初始化：绑定回调函数（使用类成员函数）
int FFWebSocket::init()
{
    try {
        // 初始化asio和事件循环
        wssClient.init_asio();
        wssClient.start_perpetual();

        // 绑定回调函数到当前实例的纯虚函数
        wssClient.set_open_handler(
            bind(&FFWebSocket::on_open, this, ::_1)
        );
        wssClient.set_close_handler(
            bind(&FFWebSocket::on_close, this, ::_1)
        );
        wssClient.set_message_handler(
            bind(&FFWebSocket::on_message, this, ::_1, ::_2)
        );
        wssClient.set_fail_handler(
            bind(&FFWebSocket::on_fail, this, ::_1)
        );

        return 0;
    }
    catch (websocketpp::exception const& e) {
        std::cout << "初始化失败：" << e.what() << std::endl;
        return 1;
    }
}

// 连接服务器
int FFWebSocket::connect(const std::string uri_)
{
    if (connected_) {
        return WEBSOCKET_FAIL;
    }

    wssUri = uri_;
    websocketpp::lib::error_code ec;
    client::connection_ptr con = wssClient.get_connection(wssUri, ec);

    if (ec) {
        std::cout << "create connection failed: " << ec.message() << std::endl;
        return WEBSOCKET_FAIL;
    }

    // 保存连接句柄
    wssHdl = con->get_handle();
    wssClient.connect(con);

    return WEBSOCKET_SUCESS;
}

// 发送消息
int FFWebSocket::send(const std::string msg)
{
    if (!connected_) {
        return WEBSOCKET_AGAIN;
    }

    try {
        wssClient.send(wssHdl, msg, websocketpp::frame::opcode::text);
        std::cout << "send message sucessfully: " << msg << std::endl;
        return 0;
    }
    catch (websocketpp::exception const& e) {
        std::cout << "send message failed: " << e.what() << std::endl;
        return 1;
    }
}

// 关闭连接
int FFWebSocket::close()
{
    if (!connected_) {
        return WEBSOCKET_FAIL;
    }
    try {
        websocketpp::lib::error_code ec;
        wssClient.close(wssHdl, websocketpp::close::status::normal, "主动关闭连接", ec);
        wssClient.stop();
        if (ec) {
            std::cout << "关闭连接失败: " << ec.message() << std::endl;
            return 1;
        }

        // 重置连接状态
        wssHdl.reset();
        wssUri.clear();
        return 0;
    }
    catch (websocketpp::exception const& e) {
        std::cout << "关闭异常: " << e.what() << std::endl;
        return 1;
    }
    catch (...) {
        std::cout << "关闭时发生未知异常" << std::endl;
        return 1;
    }
}

// 运行事件循环
int FFWebSocket::exec()
{
    try {
        wssClient.run();
        return 0;
    }
    catch (websocketpp::exception const& e) {
        std::cout << "WebSocket异常: " << e.what() << std::endl;
        return 1;
    }
    catch (...) {
        std::cout << "未知异常" << std::endl;
        return 1;
    }
}

int FFWebSocket::exec_one()
{
    try {
        wssClient.run_one();
        return 0;
    }
    catch (websocketpp::exception const& e) {
        std::cout << "WebSocket异常: " << e.what() << std::endl;
        return 1;
    }
    catch (...) {
        std::cout << "未知异常" << std::endl;
        return 1;
    }
}

//开启一个线程，运行事件循环
int FFWebSocket::asyncExec()
{
    std::thread t([this]() {
        try {
            wssClient.run();
        }
        catch (websocketpp::exception const& e) {
            std::cout << "WebSocket异常: " << e.what() << std::endl;
        }
        catch (...) {
            std::cout << "未知异常" << std::endl;
        }
        });
    t.detach();

    return 0;
}
